package com.uzai.console.service.mini.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.uzai.common.exception.BusinessException;
import com.uzai.common.result.ResponseCode;
import com.uzai.console.common.utils.DateUtil;
import com.uzai.console.common.utils.Tools;
import com.uzai.console.dto.BaseDto;
import com.uzai.console.dto.mini.minigoods.*;
import com.uzai.console.entity.MiniGoods;
import com.uzai.console.mapper.MiniGoodsMapper;
import com.uzai.console.service.feign.UzaiCmsFeignService;
import com.uzai.console.service.mini.MiniGoodsService;
import com.uzai.console.vo.mini.minigoods.MiniGoodsVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author liuqi
 * @date 2021年08月23日 20:25
 */
@Service
public class MiniGoodsServiceImpl implements MiniGoodsService {

    @Autowired
    private MiniGoodsMapper miniGoodsMapper;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 分页查询小程序团购商品列表
     * @author liuqi
     * @date 2021/8/13 11:38
     * @return MiniGoodsVo
     */
    public Page<MiniGoodsVo> findMiniGoodsByPage(MiniGoodsQuery miniGoodsQuery){
        //新建返回到页面的LIST对象
        List<MiniGoodsVo> miniGoodsVoList = new ArrayList<>();
        //返回到页面分页对象
        Page<MiniGoodsVo> pageVo = new Page<>();

        //默认排序
        List<OrderItem> orderItemList = miniGoodsQuery.getOrderItemList();
        if(orderItemList == null || orderItemList.size() == 0){
            orderItemList = new ArrayList<>();
            orderItemList.add(OrderItem.asc("pageOrder"));
            orderItemList.add(OrderItem.desc("publishStartTime"));
            miniGoodsQuery.setOrderItemList(orderItemList);
        }

        //执行分页查询对象
        Page<MiniGoods> page = new Page<>();
        miniGoodsQuery.convert(page);
        List<MiniGoods> miniGoodsList = miniGoodsMapper.findByList(page, miniGoodsQuery);

        if(miniGoodsList != null && miniGoodsList.size() > 0){
            for (MiniGoods miniGoods : miniGoodsList){
                MiniGoodsVo miniGoodsVo = new MiniGoodsVo();
                BeanUtils.copyProperties(miniGoods, miniGoodsVo);
                if(StringUtils.isNotBlank(miniGoods.getImgs())){
                    try {
                       List<String> imgsList = JSONArray.parseArray(miniGoods.getImgs(), String.class);
                        miniGoodsVo.setImgsList(imgsList);

                        //如果是官方商品，得显示官方得库存和访问量
                        if(miniGoods.getSource() == 0){//官方商品
                            //访问量
                            String ITEM_VIEW_NUM_CACHE_KEY = "mini_item_view_num_" + miniGoods.getSourceId();
                            Object clickCount = redisTemplate.opsForValue().get(ITEM_VIEW_NUM_CACHE_KEY);
                            if (clickCount != null) {
                                miniGoodsVo.setClickCount((Integer) clickCount);
                            }

                            //官方商品库存量
                            MiniGoods miniGoods_god = miniGoodsMapper.selectById(miniGoods.getSourceId(), 8888L);
                            if(miniGoods_god == null){
                                miniGoodsVo.setTotal(miniGoods_god.getTotal());
                            }
                        }

                    }catch (Exception e){

                    }
                }

                miniGoodsVoList.add(miniGoodsVo);
            }
        }

        BeanUtils.copyProperties(page, pageVo);
        pageVo.setRecords(miniGoodsVoList);
        //将分页信息复制到返回到页面的分页MO当中
        return pageVo;
    }

    /**
     * 查询小程序团购商品详情
     * @author liuqi
     * @date 2021/8/13 11:38
     * @return MiniGoodsVo
     */
    public MiniGoodsVo findMiniGoodsById(MiniGoodsIdDto miniGoodsIdDto){

        //返回的对象
        MiniGoodsVo miniGoodsVo = new MiniGoodsVo();

        if(miniGoodsIdDto.getId() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入id");
        }

        MiniGoods miniGoods = miniGoodsMapper.selectById(miniGoodsIdDto.getId(), miniGoodsIdDto.getMerId());
        if(miniGoods == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该商品不存在");
        }

        BeanUtils.copyProperties(miniGoods, miniGoodsVo);

        if(StringUtils.isNotBlank(miniGoods.getImgs())){
            try {
                List<String> imgsList = JSONArray.parseArray(miniGoods.getImgs(), String.class);
                miniGoodsVo.setImgsList(imgsList);

                //如果是官方商品，得显示官方得库存和访问量
                if(miniGoods.getSource() == 0){//官方商品
                    //访问量
                    String ITEM_VIEW_NUM_CACHE_KEY = "mini_item_view_num_" + miniGoods.getSourceId();
                    Object clickCount = redisTemplate.opsForValue().get(ITEM_VIEW_NUM_CACHE_KEY);
                    if (clickCount != null) {
                        miniGoodsVo.setClickCount((Integer) clickCount);
                    }

                    //官方商品库存量
                    MiniGoods miniGoods_god = miniGoodsMapper.selectById(miniGoods.getSourceId(), 8888L);
                    if(miniGoods_god == null){
                        miniGoodsVo.setTotal(miniGoods_god.getTotal());
                    }
                }
            }catch (Exception e){

            }
        }

        return miniGoodsVo;
    }

    /**
     * 修改小程序团购商品详情
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param miniGoodsDto
     * @return null
     */
    public void addMiniGoods(MiniGoodsDto miniGoodsDto){

        if(StringUtils.isBlank(miniGoodsDto.getItemId())){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "商品id不能为空");
        }

        if(StringUtils.isBlank(miniGoodsDto.getItemTitle())){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "商品标题不能为空");
        }

        int now = DateUtil.getNowTime();

        MiniGoods miniGoods = new MiniGoods();
        miniGoods.setId(IdWorker.getId());
        miniGoods.setMerId(miniGoodsDto.getMerId());
        miniGoods.setSource(1);//运营商自己的商品
        miniGoods.setItemId(miniGoodsDto.getItemId());
        miniGoods.setItemTitle(miniGoodsDto.getItemTitle());
        miniGoods.setPrice(Tools.getDouble(miniGoodsDto.getPrice()));
        miniGoods.setTgPrice(Tools.getDouble(miniGoodsDto.getTgPrice()));
        miniGoods.setImgs(JSONObject.toJSONString(miniGoodsDto.getImgsList()));
        miniGoods.setDetail(miniGoodsDto.getDetail());
        miniGoods.setTotal(miniGoodsDto.getTotal());
        miniGoods.setStoreCount(miniGoodsDto.getTotal()); //添加时，库存量默认等于总量
        miniGoods.setSaleCount(0); //销量默认为0
        miniGoods.setPublishName(miniGoodsDto.getPublishName());
        miniGoods.setPublishHeadImg(miniGoodsDto.getPublishHeadImg());
        miniGoods.setPublishStartTime(miniGoodsDto.getPublishStartTime());
        miniGoods.setPublishEndTime(0); //没有发布结束时间
        miniGoods.setStatus(1); //默认上架
        miniGoods.setRemark(null);
        miniGoods.setVersion(0);
        miniGoods.setPageOrder(0);    //默认排序都为0
        miniGoods.setShowStatus(0);   //默认关闭
        miniGoods.setCreateTime(now);
        miniGoods.setUpdateTime(now);

        miniGoodsMapper.insertSelective(miniGoods);

    }

    /**
     * 修改小程序团购商品详情
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param miniGoodsDto
     * @return null
     */
    public void updateMiniGoods(MiniGoodsDto miniGoodsDto){

        if(miniGoodsDto.getId() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入id");
        }

        MiniGoods miniGoods = miniGoodsMapper.selectById(miniGoodsDto.getId(), miniGoodsDto.getMerId());

        if(miniGoods == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该商品不存在");
        }

        if(miniGoods.getSource()==0){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "不能修改官方团购商品");
        }

        if(StringUtils.isBlank(miniGoodsDto.getItemId())){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "商品id不能为空");
        }

        if(StringUtils.isBlank(miniGoodsDto.getItemTitle())){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "商品标题不能为空");
        }

        int now = DateUtil.getNowTime();

        miniGoods.setItemId(miniGoodsDto.getItemId());
        miniGoods.setItemTitle(miniGoodsDto.getItemTitle());
        miniGoods.setPrice(Tools.getDouble(miniGoodsDto.getPrice()));
        miniGoods.setTgPrice(Tools.getDouble(miniGoodsDto.getTgPrice()));
        miniGoods.setImgs(JSONObject.toJSONString(miniGoodsDto.getImgsList()));
        miniGoods.setDetail(miniGoodsDto.getDetail());
        miniGoods.setPublishName(miniGoodsDto.getPublishName());
        miniGoods.setPublishHeadImg(miniGoodsDto.getPublishHeadImg());
        miniGoods.setPublishStartTime(miniGoodsDto.getPublishStartTime());
        miniGoods.setPublishEndTime(0);
        miniGoods.setRemark(null);
        miniGoods.setUpdateTime(now);
        miniGoodsMapper.updateById(miniGoods);

    }

    /**
     * 删除小程序团购商品信息
     * @author liuqi
     * @date 2021/8/13 11:38
     * @return null
     */
    public void deleteMiniGoods(MiniGoodsIdDto miniGoodsIdDto){
        if(miniGoodsIdDto.getId() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入id");
        }

        MiniGoods miniGoods = miniGoodsMapper.selectById(miniGoodsIdDto.getId(), miniGoodsIdDto.getMerId());

        if(miniGoods == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该商品不存在");
        }

        if(miniGoods.getSource()==0){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "不能删除官方团购商品");
        }

        miniGoodsMapper.deleteById(miniGoodsIdDto.getId(), miniGoodsIdDto.getMerId());

    }


    /**
     * 修改小程序团购淘宝的库存量
     * @author liuqi
     * @date 2021/8/13 11:38
     * @return null
     */
    public void updateMiniGoodsStoreCount(MiniGoodsStoreCountDto miniGoodsStoreCountDto){
        if(miniGoodsStoreCountDto.getId() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入id");
        }

        MiniGoods miniGoods = miniGoodsMapper.selectById(miniGoodsStoreCountDto.getId(), miniGoodsStoreCountDto.getMerId());

        if(miniGoods == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该商品不存在");
        }

        if(miniGoods.getSource()==0){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "不能修改官方团购商品");
        }

        if(miniGoodsStoreCountDto.getUpdateStoreCount() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入修改的库存量");
        }

        int total = miniGoods.getTotal() + miniGoodsStoreCountDto.getUpdateStoreCount();
        if(total < 0){
            total = 0;  //如果总量小于0，则默认为0
        }

        int storeCount = miniGoods.getStoreCount() + miniGoodsStoreCountDto.getUpdateStoreCount();
        if(storeCount < 0 ){
            storeCount = 0; //如果库存量小于0，则默认为0
        }

        miniGoods.setTotal(total);
        miniGoods.setStoreCount(storeCount);
        miniGoods.setUpdateTime(DateUtil.getNowTime());

        int j = miniGoodsMapper.updateStoreCount(miniGoods);

        if(j != 1){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "网络错误");
        }
    }

    /**
     * 修改小程序团购商品的在线状态
     * @author liuqi
     * @date 2021/8/13 11:38
     * @return null
     */
    public void updateMiniGoodsStatus(MiniGoodsStatusDto miniGoodsStatusDto){
        if(miniGoodsStatusDto.getId() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入id");
        }

        MiniGoods miniGoods = miniGoodsMapper.selectById(miniGoodsStatusDto.getId(), miniGoodsStatusDto.getMerId());

        if(miniGoods == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该商品不存在");
        }

        if(miniGoods.getSource()==0){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "不能修改官方团购商品");
        }

        miniGoods.setStatus(Tools.getInteger(miniGoodsStatusDto.getStatus()));
        miniGoods.setUpdateTime(DateUtil.getNowTime());

        miniGoodsMapper.updateStatus(miniGoods);
    }

    /**
     * 修改小程序团购商品是否显示
     * @author liuqi
     * @date 2021/8/13 11:38
     * @return null
     */
    public void updateMiniGoodsShowStatus(MiniGoodsShowStatusDto miniGoodsShowStatusDto){
        if(miniGoodsShowStatusDto.getId() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入id");
        }

        MiniGoods miniGoods = miniGoodsMapper.selectById(miniGoodsShowStatusDto.getId(), miniGoodsShowStatusDto.getMerId());

        if(miniGoods == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该商品不存在");
        }

        miniGoods.setShowStatus(Tools.getInteger(miniGoodsShowStatusDto.getShowStatus()));
        miniGoods.setUpdateTime(DateUtil.getNowTime());

        miniGoodsMapper.updateShowStatus(miniGoods);
    }

    /**
     * 修改小程序团购商品的页面排序
     * @author liuqi
     * @date 2021/8/13 11:38
     * @return null
     */
    public void updateMiniGoodsPageOrder(MiniGoodsPageOrderDto miniGoodsPageOrderDto){
        if(miniGoodsPageOrderDto.getId() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入id");
        }

        MiniGoods miniGoods = miniGoodsMapper.selectById(miniGoodsPageOrderDto.getId(), miniGoodsPageOrderDto.getMerId());

        if(miniGoods == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该商品不存在");
        }

        miniGoods.setPageOrder(Tools.getInteger(miniGoodsPageOrderDto.getPageOrder()));
        miniGoods.setUpdateTime(DateUtil.getNowTime());

        miniGoodsMapper.updatePageOrder(miniGoods);
    }

    /**
     * 一键同步官方平台小程序团购商品
     * @author liuqi
     * @date 2021/8/13 11:38
     * @return null
     */
    public void useGodMiniGoods(BaseDto baseDto){

        if(baseDto.getMerId() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "没有运营商id");
        }

        int now = DateUtil.getNowTime();

        MiniGoodsQuery miniGoodsQuery = new MiniGoodsQuery();
        miniGoodsQuery.setMerId(8888L);
        List<MiniGoods> miniGoodsList = miniGoodsMapper.findByList(miniGoodsQuery);
        if(miniGoodsList != null && miniGoodsList.size() > 0){
            for (MiniGoods miniGoods_god : miniGoodsList) {
                Long sourceId = miniGoods_god.getId();
                //查询运营商是否已经有这个官方团购商品了
                MiniGoods miniGoods_old = miniGoodsMapper.selectBySourceId(sourceId, baseDto.getMerId());
                if(miniGoods_old != null){//存在，则修改
                    miniGoods_old.setItemId(miniGoods_god.getItemId());
                    miniGoods_old.setItemTitle(miniGoods_god.getItemTitle());
                    miniGoods_old.setPrice(miniGoods_god.getPrice());
                    miniGoods_old.setTgPrice(miniGoods_god.getTgPrice());
                    miniGoods_old.setImgs(miniGoods_god.getImgs());
                    miniGoods_old.setDetail(miniGoods_god.getDetail());
                    miniGoods_old.setTotal(miniGoods_god.getTotal());
                    miniGoods_old.setStoreCount(miniGoods_god.getStoreCount());
                    miniGoods_old.setPublishName(miniGoods_god.getPublishName());
                    miniGoods_old.setPublishHeadImg(miniGoods_god.getPublishHeadImg());
                    miniGoods_old.setPublishStartTime(miniGoods_god.getPublishStartTime());
                    miniGoods_old.setPublishEndTime(miniGoods_god.getPublishEndTime());
                    miniGoods_old.setStatus(miniGoods_god.getStatus());
                    miniGoods_old.setRemark(miniGoods_god.getRemark());
                    miniGoods_old.setVersion(miniGoods_god.getVersion());
                    miniGoods_old.setUpdateTime(now);
                    miniGoodsMapper.updateByIdSelective(miniGoods_old);
                }else{ //不存在，则添加
                    MiniGoods miniGoods_new = new MiniGoods();
                    miniGoods_new.setId(IdWorker.getId());
                    miniGoods_new.setMerId(baseDto.getMerId());
                    miniGoods_new.setSource(0);
                    miniGoods_new.setSourceId(sourceId);
                    miniGoods_new.setItemId(miniGoods_god.getItemId());
                    miniGoods_new.setItemTitle(miniGoods_god.getItemTitle());
                    miniGoods_new.setPrice(miniGoods_god.getPrice());
                    miniGoods_new.setTgPrice(miniGoods_god.getTgPrice());
                    miniGoods_new.setImgs(miniGoods_god.getImgs());
                    miniGoods_new.setDetail(miniGoods_god.getDetail());
                    miniGoods_new.setTotal(miniGoods_god.getTotal());
                    miniGoods_new.setStoreCount(miniGoods_god.getStoreCount());
                    miniGoods_new.setSaleCount(0); //销量为运营商的销量
                    miniGoods_new.setPublishName(miniGoods_god.getPublishName());
                    miniGoods_new.setPublishHeadImg(miniGoods_god.getPublishHeadImg());
                    miniGoods_new.setPublishStartTime(miniGoods_god.getPublishStartTime());
                    miniGoods_new.setPublishEndTime(miniGoods_god.getPublishEndTime());
                    miniGoods_new.setStatus(miniGoods_god.getStatus());
                    miniGoods_new.setRemark(miniGoods_god.getRemark());
                    miniGoods_new.setVersion(miniGoods_god.getVersion());
                    miniGoods_new.setPageOrder(0);  //页面排序为0
                    miniGoods_new.setShowStatus(0); //默认显示
                    miniGoods_new.setCreateTime(now);
                    miniGoods_new.setUpdateTime(now);
                    miniGoodsMapper.insertSelective(miniGoods_new);
                }
            }
        }
    }


}
